package com.huanghj.book.listener;




import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * SOA启动监听器
 * 
 * @author Hungel.zou
 * @time 2015年8月5日 上午10:37:22
 */
public class SoaStartupListener extends ContextLoaderListener implements ServletContextListener{
	
	private static final Logger log = LoggerFactory.getLogger(SoaStartupListener.class);
	
	public void contextInitialized(ServletContextEvent event) {
		if (log.isDebugEnabled()) {
			log.debug("initializing context...");
		}

		ServletContext context = event.getServletContext();
		setServletContext(context);

		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		setAppContext(ctx);

		//checkDataSource("jdbc/storeApp");
		//checkDataSource("jdbc/crm");
		//checkDataSource("jdbc/ams");
	}
	
	protected void checkDataSource(String jndiName) {
		Connection conn = null;
		try {
			Context initCtx = new InitialContext();
			DataSource dataSource = (DataSource) initCtx.lookup("java:comp/env/" + jndiName);
			if (dataSource == null) {
				throw new Exception("无法连接数据源：" + jndiName);
			} else {
				conn = dataSource.getConnection();
				if (conn == null) {
					log.error("无法从数据源获取连接：" + jndiName);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					//
				}
			}
		}
	}

	public static Object getBean(String beanName) {
		return appContext.getBean(beanName);
	}

	/**
	 */
	private static ApplicationContext appContext;

	public static ApplicationContext getAppContext() {
		return appContext;
	}

	public static void setAppContext(ApplicationContext ctx) {
		appContext = ctx;
	}

	/**
	 * ServletContext
	 */
	private static ServletContext servletContext;

	/**
	 * @return Returns the servletContext.
	 */
	public static ServletContext getServletContext() {
		return servletContext;
	}

	/**
	 * @param servletContext
	 *            The servletContext to set.
	 */
	public static void setServletContext(ServletContext servletContext) {
		SoaStartupListener.servletContext = servletContext;
	}
}
